package com.fyk.controller;

import com.fyk.entity.User;
import com.fyk.service.UserService;
import com.fyk.utils.VerificationCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //注册
    @RequestMapping("registered")
    public String registered(User user, MultipartFile img){
        log.info("注册用户名:{},注册密码: {},注册真实姓名: {}",user.getUserName(),user.getPassword(),user.getRealName());
        log.info("上传文件名: {},上传文件大小: {}",img.getOriginalFilename(),img.getSize());
        //暂时没有对上传文件做处理
        user.setPhotoPath("xxx");
        userService.addUser(user);
        return "redirect:/login";
    }

    //登录
    @RequestMapping("login")
    public String login(User user,String loginCode,HttpSession session, Model model){
        log.info("用户名: {},密码: {},登录验证码: {}",user.getUserName(),user.getPassword(),loginCode);
        //先判断session中的验证码是否过期
        if (ObjectUtils.isEmpty(session.getAttribute("code"))){
            model.addAttribute("msg","登录超时,请重新登录");
            return "login";
        }
        log.info("session存储的验证码: {}",session.getAttribute("code").toString());
        //再判断验证码是否正确
        if(!loginCode.equalsIgnoreCase(session.getAttribute("code").toString())){
            model.addAttribute("msg","验证码错误,请重新登录");
            return "login";
        }
        //最后判断用户名和登录密码是否正确
        try {
            if (userService.queryUserByUserName(user)){
                return "index";
            }
        } catch (Exception e) {
            model.addAttribute("msg",e.getMessage());
        }
        return "login";
    }

    //生成验证码
    @RequestMapping("verification")
    public void verification(HttpSession session, HttpServletResponse response) throws IOException {
        //通过工具类获得随机数
        String code = VerificationCode.generateVerifyCode(4);
        //将获得的随机数存储在session中,以便后续验证
        session.setAttribute("code",code);
        //通过工具类将随机数转化为图片发送到前端
        ServletOutputStream os = response.getOutputStream();
        VerificationCode.outputImage(110,45,os,code);
    }

}
